package com.hzhr.iot.cqgas.ds.controller;

import com.hzhr.iot.core.constant.CommonOptions;
import com.hzhr.iot.core.util.HzhrTypeUtil;
import com.hzhr.iot.cqgas.ds.dao.device.custom.DeviceDao;
import com.hzhr.iot.cqgas.ds.dao.device.example.DevCollectDeviceDao;
import com.hzhr.iot.cqgas.ds.dao.smartmeter.custom.SmDao;
import com.hzhr.iot.cqgas.ds.dao.toll.custom.TollGasUserCustomDao;
import com.hzhr.iot.cqgas.ds.dao.toll.example.TollGasUserDao;
import com.hzhr.iot.cqgas.ds.dao.user.custom.UserCustomDao;
import com.hzhr.iot.cqgas.ds.entity.device.DevCollectDeviceEntity;
import com.hzhr.iot.cqgas.ds.entity.device.DevCollectDeviceExample;
import com.hzhr.iot.cqgas.ds.entity.toll.TollGasUserEntity;
import com.hzhr.iot.cqgas.ds.entity.user.UsrDeptEntity;
import com.hzhr.iot.cqgas.ds.entity.user.UsrDeptExample;
import com.hzhr.iot.cqgas.ds.service.CollectDeviceService;
import com.hzhr.iot.cqgas.ds.service.DeptService;
import com.hzhr.iot.cqgas.ds.service.TollOptionsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
public class LoraMeterController {
    @Autowired
    DevCollectDeviceDao devCollectDeviceDao;
    @Autowired
    DeviceDao deviceDao;
    @Autowired
    SmDao smDao;
    @Autowired
    UserCustomDao userCustomDao;
    @Autowired
    TollGasUserCustomDao tollGasUserCustomDao;
    @Autowired
    TollGasUserDao tollGasUserDao;
    @Autowired
    TollOptionsService tollOptionsService;

    private Logger logger = LoggerFactory.getLogger(LoraMeterController.class);

    @Value("${companyId}")
    String companyId;

    @RequestMapping(value = "/syncLoraMeter")
    public void syncLoraMeter() {
        int addCount = 0;
        int updateCount = 0;
        long startTime = new Date().getTime();

        String resident = tollOptionsService.getCode("GAS_USER_TYPE", "RESIDENTIAL_USER");
        String commercial = tollOptionsService.getCode("GAS_USER_TYPE", "COMMERCIAL_USER");

        int i = 0;
        while (true) {
            Integer count = 5000;
            Integer start =  i * count;

            //查询平台自建的lora表的代码
            List<String> codes = deviceDao.select14(start, count);
            for (String code :
                    codes) {
                try {
                    //根据平台自建的lora表的代码找到这些表的营销系统信息
                    Map<String, Object> loraMeter = smDao.select3(code);
                    if (loraMeter != null) {
                        String ORG_ID = HzhrTypeUtil.object2string(loraMeter.get("ORG_ID"));
                        String YQDZ_YQZH = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_YQZH"));
                        String YQDZ_HZ_MC = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_HZ_MC"));
                        String YQDZ_SM = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_SM"));
                        String yqdzKhLx = HzhrTypeUtil.object2string(loraMeter.get("YQDZ_KH_LX"));

                        //根据orgId找到部门
                        String deptCode = ORG_ID.replaceFirst("0000", "9-01");
                        Map<String, Object> dept = userCustomDao.select7(deptCode);
                        if (dept == null) continue;

                        //根据yqdzYqzh找到燃气用户编号，如果过找不到燃气用户则自建燃气用户
                        Integer gasUserId = tollGasUserCustomDao.select3(YQDZ_YQZH);
                        if (gasUserId == null) {
                            TollGasUserEntity tollGasUserEntity = new TollGasUserEntity();
                            tollGasUserEntity.setCode(YQDZ_YQZH);
                            tollGasUserEntity.setName(YQDZ_HZ_MC != null ? YQDZ_HZ_MC : "未知");
                            tollGasUserEntity.setAddress(YQDZ_SM);
                            if ("1".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(commercial);
                            } else if ("2".equals(yqdzKhLx)) {
                                tollGasUserEntity.setTypeCode(resident);
                            } else {
                                tollGasUserEntity.setTypeCode("0");
                            }
                            tollGasUserEntity.setCompanyId(Integer.parseInt(companyId));
                            tollGasUserEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                            tollGasUserEntity.setCreateTime(new Date());
                            tollGasUserEntity.setCreateUserId(0);
                            tollGasUserEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                            tollGasUserEntity.setIsValid(CommonOptions.YES_NO.YES);
                            tollGasUserEntity.setState("1");
                            tollGasUserDao.insert(tollGasUserEntity);

                            gasUserId = tollGasUserEntity.getId();
                        }

                        //根据营销系统信息更新这些lora表
                        DevCollectDeviceEntity devCollectDeviceEntity = new DevCollectDeviceEntity();
                        devCollectDeviceEntity.setCompanyId(9);
                        devCollectDeviceEntity.setDeptId(HzhrTypeUtil.object2integer(dept.get("ID")));
                        devCollectDeviceEntity.setDeptCode(deptCode);
                        devCollectDeviceEntity.setResourceCode(HzhrTypeUtil.object2string(dept.get("RESOURCE_CODE")));
                        devCollectDeviceEntity.setGasUserId(gasUserId);
                        devCollectDeviceEntity.setGasUserName(YQDZ_HZ_MC);
                        devCollectDeviceEntity.setGasUserCode(YQDZ_YQZH);
                        devCollectDeviceEntity.setGasUserAddress(YQDZ_SM);
                        devCollectDeviceEntity.setUpdateUserId(0);
                        devCollectDeviceEntity.setUpdateTime(new Date());
                        DevCollectDeviceExample devCollectDeviceExample = new DevCollectDeviceExample();
                        devCollectDeviceExample.createCriteria().andCodeEqualTo(code).andIsValidEqualTo("1");
                        devCollectDeviceDao.updateByExampleSelective(devCollectDeviceEntity, devCollectDeviceExample);
                        updateCount++;
                    }
                } catch (Throwable e) {
                    logger.error("同步lora表信息异常", e);
                }
            }

            if (codes.size() < 5000) {
                break;
            }

            i++;
        }

        long endTime = new Date().getTime();
        logger.info("更新自建lora表信息结束: " + (endTime - startTime) / 1000 + "s");
        logger.info("同步时间: " + (endTime - startTime) / 1000 + "s");
        logger.info("更新数量: " + updateCount + "条");
    }
}
